<?php

namespace app\guild\controller;


use app\common\model\RegSourceModel;
use app\common\model\UserModel;
use app\common\model\StatUserModel;
use app\common\model\AppDownloadModel;
use think\facade\Request;

class RegsourceController extends BaseController
{

    public function index()
    {
        return $this->fetch();
    }

    /**
     * 渠道列表
     * @return \think\response\Json
     */
    public function getlist()
    {
        $page        = Request::param("page");
        $limit       = Request::param("limit");
        $source_key  = Request::param('source_key');
        $source_name = Request::param('source_name');
        $device      = Request::param('device');

        $where = [
            ['guild_id', '=', $this->guild_id]
        ];
        if ($source_key) {
            $where[] = ['source_key', '=', $source_key];
        }

        if (is_numeric($device)) {
            $where[] = ['device', '=', $device];
        }
        if ($source_name) {
            $where[] = ['source_name', 'like', "%{$source_name}%"];
        }

        $list = RegSourceModel::with([
            'appdownload' => function ($query) {
                $query->field('count(id) as total,source')->group('source');
            }
        ])->where($where)
            ->limit(($page - 1) * $limit, $limit)
            ->order("id", "desc")
            ->select();

        if (count($list) > 0) {
            $count = RegSourceModel::where($where)->count();
            // 重新组合数组
            foreach ($list as &$item) {
                if ($this->guild_info->download_ratio > 0 && !empty($item->appdownload)) {
                    $download_ratio           = bcsub(1, bcdiv($this->guild_info->download_ratio, 100, 2), 2);
                    if ($this->guild_info->download_reserved > 0 && ($item->appdownload->total > $this->guild_info->download_reserved)) {
                        $item->appdownload->total = $this->guild_info->download_reserved + ceil(bcmul(($item->appdownload->total - $this->guild_info->download_reserved), $download_ratio, 2));
                    }
                }

                $item['reg_count'] = UserModel::where("reg_source_id", $item['source_key'])->count();
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function stat()
    {

        $list = RegSourceModel::with([
            'appdownload' => function ($query) {
                $query->field('count(id) as total,source')->group('source');
            }
        ])->where([['guild_id', '=', $this->guild_id]])->order("id", "desc")
            ->select();
        if (count($list) > 0) {
            $count = RegSourceModel::count();
            // 重新组合数组
            foreach ($list as &$item) {
                if ($this->guild_info->download_ratio > 0 && !empty($item->appdownload)) {
                    $download_ratio           = bcsub(1, bcdiv($this->guild_info->download_ratio, 100, 2), 2);
                    // $item->appdownload->total = ceil(bcmul($item->appdownload->total, $download_ratio, 2));
                    if ($this->guild_info->download_reserved > 0 && ($item->appdownload->total > $this->guild_info->download_reserved)) {
                        $item->appdownload->total = $this->guild_info->download_reserved + ceil(bcmul(($item->appdownload->total - $this->guild_info->download_reserved), $download_ratio, 2));
                    }
                }

                $item['reg_count'] = UserModel::where("reg_source_id", $item['source_key'])->count();
            }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function date_stat()
    {
        // 近七天
        $date_range = [
            ['start' => date("Y-m-d 00:00:00"), 'end' => date("Y-m-d 23:59:59")],    //今天，每一条是往前一天
            ['start' => date("Y-m-d 00:00:00", time() - 86400), 'end' => date("Y-m-d 23:59:59", time() - 86400)],
            ['start' => date("Y-m-d 00:00:00", time() - 86400 * 2), 'end' => date("Y-m-d 23:59:59", time() - 86400 * 2)],
            ['start' => date("Y-m-d 00:00:00", time() - 86400 * 3), 'end' => date("Y-m-d 23:59:59", time() - 86400 * 3)],
            ['start' => date("Y-m-d 00:00:00", time() - 86400 * 4), 'end' => date("Y-m-d 23:59:59", time() - 86400 * 4)],
            ['start' => date("Y-m-d 00:00:00", time() - 86400 * 5), 'end' => date("Y-m-d 23:59:59", time() - 86400 * 5)],
            ['start' => date("Y-m-d 00:00:00", time() - 86400 * 6), 'end' => date("Y-m-d 23:59:59", time() - 86400 * 6)],
        ];

        $download_ratio = bcsub(1, bcdiv($this->guild_info->download_ratio, 100, 2), 2);

        $sources = RegSourceModel::where([['guild_id', '=', $this->guild_id]])->order("id", "desc")->select();
        $list = [];
        for ($i = 0; $i < count($date_range); $i++) {
            for ($j = 0; $j < count($sources); $j++) {
                $combine = [];
                $combine['date'] = date("Y-m-d", strtotime($date_range[$i]['start']));
                $combine['source_key'] = $sources[$j]['source_key'];
                $combine['source_name'] = $sources[$j]['source_name'];
                $combine['device'] = $sources[$j]['device'];
                $combine['url'] = $sources[$j]['url'];
                $sum_download = AppDownloadModel::where([['time', '>=', $date_range[$i]['start']], ['time', '<=', $date_range[$i]['end']], ['source', '=', $sources[$j]['source_key']]])->count();
                if ($this->guild_info->download_reserved > 0 && ($sum_download > $this->guild_info->download_reserved)) {
                    $combine['down_total'] = $this->guild_info->download_reserved + ceil(bcmul($sum_download - $this->guild_info->download_reserved, $download_ratio, 2));;
                } else {
                    $combine['down_total'] = $sum_download;
                }

                $combine['reg_count'] =  UserModel::where([['regist_time', '>=', $date_range[$i]['start']], ['regist_time', '<=', $date_range[$i]['end']], ['reg_source_id', '=', $sources[$j]['source_key']]])->count();
                $list[] = $combine;
            }
        }

        if (count($list) > 0) {
            // $count = RegSourceModel::count();
            // // 重新组合数组
            // foreach ($list as &$item) {
            //     if ($this->guild_info->download_ratio > 0 && !empty($item->appdownload)) {
            //         $download_ratio           = bcsub(1, bcdiv($this->guild_info->download_ratio, 100, 2), 2);
            //         $item->appdownload->total = ceil(bcmul($item->appdownload->total, $download_ratio, 2));
            //     }

            //     $item['reg_count'] = UserModel::where("reg_source_id", $item['source_key'])->count();
            // }

            return json(["code" => 0, "msg" => "", "data" => $list, "count" => count($list)]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 每日数据
     * @return mixed
     */
    public function everyday()
    {
        $source_key = Request::param('source_key');
        $start_time = Request::param('start_time');
        $this->assign('source_key', $source_key);
        $this->assign('start_time', $start_time);
        return $this->fetch();
    }

    public function everyday_list()
    {
        $source_key = Request::param('source_key');
        $time_type  = Request::param("type");
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");

        $page  = Request::param("page");
        $limit = Request::param("limit");

        switch ($time_type) {
            case 0:
                $end_time = $end_time . ' 23:59:59';
                break;
            case 1:
                $start_time = date('Y-m-d', time());
                $end_time = date('Y-m-d 23:59:59', time());
                break;
            case 2:
                // 昨日
                $start_time = date('Y-m-d', strtotime('-1 day'));
                $end_time   = date('Y-m-d 23:59:59', strtotime($start_time));
                break;
            case 3:
                // 本周
                $w          = date('w', time());
                $start_time = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - $w + 1, date('Y')));
                $end_time   = date('Y-m-d 23:59:59', mktime(0, 0, 0, date('m'), date('d') + (7 - $w), date('Y')));
                break;

            case 4:
                // 本月
                $start_time = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
                $end_time   = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('t'), date('Y')));
                break;
            case 5:
                // 最近30天
                $start_time = date('Y-m-d', strtotime('-29 days'));
                break;
            case 6:
                // 上个月
                $start_time = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                $end_time   = date("Y-m-d 23:59:59", mktime(23, 59, 59, date("m"), 0, date("Y")));
                break;
        }

        $where = [];
        if ($source_key) {
            $where[] = ['source_key', '=', $source_key];
        }
        if ($start_time) {
            $where[] = ['date', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['date', '<=', $end_time];
        }


        $list = StatUserModel::with('regsource')->where($where)
            ->limit(($page - 1) * $limit, $limit)
            ->order("date", "desc")
            ->select();


        if (count($list) > 0) {
            $count = StatUserModel::where($where)->count();

            foreach ($list as &$item) {
                // 查询昨日登录用户
                $y_day = date('Y-m-d', strtotime('-1 day', strtotime($item->date)));
                // 留存率
                $item->retention = $item->last_day_loggin > 0 ? round(($item->next_day_user / $item->last_day_loggin) * 100, 2) : 0;
                // 下载量
                $dlwhere = [];
                $dlwhere[] = ['source', '=', $item['source_key']];
                $day_s = date('Y-m-d', strtotime($item->date));
                $dlwhere[] = ['time', '>=', $day_s];
                $dlwhere[] = ['time', '<=', $day_s . ' 23:59:59'];
                // var_dump($dlwhere);
                $item->dlcount = AppDownloadModel::where($dlwhere)->count('id');
                // echo AppDownloadModel::getLastSql();
            }

            $field        = "sum(register) as register,sum(valid_user) as valid_user,sum(loggin_user) as loggin_user,sum(active_user) as active_user";
            $statis_model = StatUserModel::where($where)->field($field)->find();

            $statis_dlwhere = [];
            $statis_dlwhere[] = ['source', '=', $source_key];
            if ($start_time) {
                $statis_dlwhere[] = ['time', '>=', $start_time];
            }
            if ($end_time) {
                $statis_dlwhere[] = ['time', '<=', $end_time];
            }

            // 汇总统计
            $statis = [
                'dl_count' => AppDownloadModel::where($statis_dlwhere)->count('id'),
                'count_days'  => StatUserModel::where($where)->group('date')->count(),
                'register'    => isset($statis_model->register) ? $statis_model->register : 0,
                'valid_user'  => isset($statis_model->valid_user) ? $statis_model->valid_user : 0,
                'loggin_user' => isset($statis_model->loggin_user) ? $statis_model->loggin_user : 0,
                'active_user' => isset($statis_model->active_user) ? $statis_model->active_user : 0,
            ];

            // echo AppDownloadModel::getLastSql();

            return json(["code" => 0, "msg" => "", "data" => $list, 'statis' => $statis, "count" => $count]);
        }
        return self::bulidFail("未查询到相关数据");
    }
}
